package com.suyx.job.controller;

import java.util.List;
import java.util.Optional;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.suyx.job.entity.AppInfo;
import com.suyx.job.entity.DeviceInfo;
import com.suyx.job.entity.Page;
import com.suyx.job.entity.Result;
import com.suyx.job.processing.ReadProcessing;
import com.suyx.job.service.IAppService;
import com.suyx.job.service.IDeviceService;
import com.suyx.job.utils.CommandUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * @Auther: suyx
 * @Date: 2018/10/31 0031 10:10
 * @Description:
 */
@Slf4j
@RestController
@RequestMapping("/app")
public class AppController  {

    private IAppService appService;
    
    private IDeviceService deviceService;

    private ReadProcessing readProcessing;
   
    @Autowired
    public AppController(IAppService appService,IDeviceService deviceService,ReadProcessing readProcessing) {
        this.appService = appService;
        this.deviceService = deviceService;
        this.readProcessing = readProcessing;
    }

    /**
     * 查询应用信息
     */
    @GetMapping(value="/findAppPage")
    public Page findAppPage(AppInfo appInfo, Integer page, Integer limit)
    {
        return appService.findAppInfoPage(appInfo,page-1,limit);
    }

    /**
     * 保存应用信息
     */
    @PostMapping("/saveApp")
    public Result saveApp(AppInfo appInfo){
        try {
        	appService.saveAndFlush(appInfo);
            return new Result(true,"保存成功!");
        }catch (Exception e){
            log.error("保存应用信息数据报错："+ExceptionUtils.getStackTrace(e));
            return new Result(false,"保存失败："+e.getMessage());
        }
    }

    /**
     * 删除应用信息
     */
    @PostMapping("deleteApp")
    public Result deleteApp(Integer appId){
        try {
        	appService.deleteById(appId);
            return new Result(true,"删除成功!");
        }catch (Exception e){
            log.error("删除应用信息数据报错：" + ExceptionUtils.getStackTrace(e));
            return new Result(false,"删除失败："+e.getMessage());
        }
    }

    @SuppressWarnings("unchecked")
	@RequestMapping("/readQyd/{deviceCode}")
    public Result readQyd(@PathVariable("deviceCode") String deviceCode){
    	Integer qyd_main_count = 40;
    	Integer qyd_child_count = 12;
        try {
        	DeviceInfo dev = new DeviceInfo();
        	dev.setDeviceCode(deviceCode);
        	Example<DeviceInfo> example = Example.of(dev);
        	Optional<DeviceInfo> deviceOp = deviceService.findOne(example);
        	DeviceInfo device  = deviceOp.get();
        	//for(DeviceInfo device :devices){
        	   if(device == null || device.getStatus() == 1){
        		   return new Result(false,deviceCode+"状态异常");//过滤状态异常的设备
        	   }
        	   AppInfo queryAppInfo = new AppInfo();
        	   queryAppInfo.setAppCode("qyd");
        	   List<AppInfo> appInfos = (List<AppInfo>) appService.findAppInfoPage(queryAppInfo, 0, 1).getData();
        	   if(appInfos.isEmpty()){
        		   return new Result(false,"appInfo is null");
        	   }
        	   //打开应用
        	   CommandUtils.excuteCommand(" adb -s "+ device.getDeviceCode() +
		                   " shell am  start -n " +
		                   appInfos.get(0).getPack()+"/" +
		                   appInfos.get(0).getMainActive()
		                  );
        	   
        	   Long startTime =  System.currentTimeMillis();
        	   Thread.sleep(8000l);
               int i = 0;
	       	   while(i <= qyd_main_count){
	       		    String cmd = "";
	       			readProcessing.swipeRead(i, device);
	       			if(i%2 == 0){
	       				cmd = "adb -s "+device.getDeviceCode() +" shell input tap 375 824";
		       			CommandUtils.excuteCommand(cmd);
		       			Thread.sleep(4000l);
		       			int j = 0;
		       			while(j <= qyd_child_count){
		       				if(readProcessing.isQydBackEvent(device.getDeviceCode())){
				       			j = qyd_child_count;
		       				}
		       				readProcessing.swipeRead(i, device);
			       			if(j == qyd_child_count){
			       				Thread.sleep(1000l);
			       				cmd = "adb -s "+device.getDeviceCode() +" shell input keyevent 4";
				       			CommandUtils.excuteCommand(cmd);
			       			}
			       			j++;
			       			log.info("qyd刷主页次数:{},看文章滑动次数:{}",i,j);
		       			}
	       			}
	       			if(i%8 == 0){
	       				cmd = "adb -s "+device.getDeviceCode() +" shell input tap 78 1300";
		       			CommandUtils.excuteCommand(cmd);
		       			Thread.sleep(4000l);
		       			log.info("qyd刷新");
	       			}
	       			if(i == qyd_main_count){
	       			 //关闭应用
	             	  CommandUtils.excuteCommand(" adb -s "+ device.getDeviceCode() +
	     		                   " shell am  force-stop " + appInfos.get(0).getPack()
	     		                   );
	       			}
	       			
	       			i++;
	       		}
	       	    Long endTime =  System.currentTimeMillis();
	       	    log.info("readQyd 执行时间："+ (endTime-startTime));
        	//}
            return new Result(true,"执行成功");
        }catch (Exception e){
            log.info("阅读app失败",e);
            return new Result(false,"阅读app失败");
        }
    }

    @RequestMapping("/readJrttjsb")
    public Result readJrttjsb(){
        try {
        	List<DeviceInfo> devices = deviceService.findAll();
        	for(DeviceInfo device :devices){
        	   if(device.getStatus() != 1){
        		   continue;//过滤状态异常的设备
        	   }
        	   AppInfo queryAppInfo = new AppInfo();
        	   queryAppInfo.setAppCode("jrttjsb");
        	   List<AppInfo> appInfos = (List<AppInfo>) appService.findAppInfoPage(queryAppInfo, 0, 1).getData();
        	   if(appInfos.isEmpty()){
        		   continue;
        	   }
        	   //打开应用
        	   CommandUtils.excuteCommand(" adb -s "+ device.getDeviceCode() +
		                   " shell am  start -n" +
		                   appInfos.get(0).getPack()+"/" +
		                   appInfos.get(0).getMainActive()
		                  );
        	   Long startTime =  System.currentTimeMillis();
        	   Thread.sleep(5000l);
               int i = 0;
	       	   while(i<40){
	       		    String cmd = "adb -s "+device.getDeviceCode() +" shell input swipe 375 824 375 600 550";
	       			CommandUtils.excuteCommand(cmd);
	       			if(i%2 == 0){
	       				cmd = "adb -s "+device.getDeviceCode() +" shell input tap 375 824";
		       			CommandUtils.excuteCommand(cmd);
		       			Thread.sleep(2000l);
		       			int j = 0;
		       			while(j < 40){
		       				if(readProcessing.isJrttjsbBackEvent(device.getDeviceCode())){
				       			j = 40;
		       				}
		       				cmd = "adb -s "+device.getDeviceCode() +" shell input swipe 375 824 375 600 550";
			       			CommandUtils.excuteCommand(cmd);
			       			if(j == 40){
			       				cmd = "adb -s "+device.getDeviceCode() +" shell input keyevent 4";
				       			CommandUtils.excuteCommand(cmd);
			       			}
			       			j++;
			       			log.info("j:"+j);
		       			}
	       			}
	       			i++;
	       		}
	       	    Long endTime =  System.currentTimeMillis();
	       	    log.info("jrttjsb 执行时间："+ (endTime-startTime));
        	}
            return new Result(true,"执行成功");
        }catch (Exception e){
            log.info("阅读app失败",e);
            return new Result(false,"阅读app失败");
        }
    }
    
    @SuppressWarnings("unchecked")
    @RequestMapping("/readSb/{deviceCode}")
       public Result readSb(@PathVariable("deviceCode") String deviceCode){
           try {
            DeviceInfo dev = new DeviceInfo();
            dev.setDeviceCode(deviceCode);
            Example<DeviceInfo> example = Example.of(dev);
            Optional<DeviceInfo> deviceOp = deviceService.findOne(example);
            DeviceInfo device  = deviceOp.get();
            //for(DeviceInfo device :devices){
               if(device == null || device.getStatus() == 0){
                return new Result(false,deviceCode+"状态异常");//过滤状态异常的设备
               }
               AppInfo queryAppInfo = new AppInfo();
               queryAppInfo.setAppCode("sb");
               List<AppInfo> appInfos = (List<AppInfo>) appService.findAppInfoPage(queryAppInfo, 0, 1).getData();
               if(appInfos.isEmpty()){
                return new Result(false,"appInfo is null");
               }
               //打开应用
               CommandUtils.excuteCommand(" adb -s "+ device.getDeviceCode() +
                        " shell am  start -n " +
                        appInfos.get(0).getPack()+"/" +
                        appInfos.get(0).getMainActive()
                       );
               Thread.sleep(8000l);
                  int i = 0;
               while(true){
                  deviceService.flush();
            Optional<DeviceInfo> deviceOp1 = deviceService.findOne(example);
            
            if(deviceOp1.get() != null && deviceOp1.get().getStatus() != 0){
             String cmd = "adb -s "+device.getDeviceCode() +" shell input swipe 527 1081 527 821 300";
             CommandUtils.excuteCommand(cmd);
             
             cmd = "adb -s "+device.getDeviceCode() +" shell input tap 644 688";
                CommandUtils.excuteCommand(cmd);
                Thread.sleep(13000l);
            }
             }
               
            //}
           }catch (Exception e){
               log.info("阅读Sb app失败",e);
               return new Result(false,"阅读Sbapp失败");
           }
       }
    
    
}
